package com.berchen.算法.查找.KMP算法;

/**
 * KMP算法
 */
public class KMP {
    public static void main(String[] args) {

        String str = "ABCD ABABCDEABC E ABCDEFG GG";
        String str2 = "ABCDEFG";
        int kmp = kmp(str, str2, createBFPPZ(str2));
        System.out.println(kmp);
    }

    public static int kmp(String str, String str2, int[] next) {
        for (int i = 0, j = 0; i < str.length(); i++) {
            while (j > 0 && str.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }

            if (str.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }

    /**
     * 生成字符串的子串的部分匹配值
     *
     * @param str
     * @return
     */
    public static int[] createBFPPZ(String str) {

        int[] result = new int[str.length()];
        result[0] = 0;
        for (int i = 1, j = 0; i < str.length(); i++) {

            while (j > 0 && str.charAt(i) != str.charAt(j)) {
                j = result[j - 1];
            }

            if (str.charAt(i) == str.charAt(j)) {
                j++;
            }
            result[i] = j;
        }
        return result;
    }
}
